package com.atguigu.szdz.dcsyl.service.impl;

import com.atguigu.szdz.dcsyl.common.utils.LasFile;
import com.atguigu.szdz.dcsyl.service.CurveDataService;
import com.atguigu.szdz.dcsyl.utils.MapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("curveDataService")
public class CurveDataServiceImpl implements CurveDataService {

    @Autowired
    MapperUtils mapperUtils;

    /**
     * 新增曲线数据
     *
     * @param curveData 曲线数据
     * @param wellId  井ID
     */
    @Override
    public void addCurveData(Map<String, List<Double>> curveData, Integer wellId) {
        //先删除该井的所有数据
        mapperUtils.updataBySql("delete from dc_curvedata where well_id=" + wellId);

        if (curveData == null || curveData.isEmpty()) {
            return;
        }

        // 获取所有键（字段名）
        List<String> keys = new ArrayList<>(curveData.keySet());

        // 构建字段列表
        StringBuilder fieldList = new StringBuilder();
        for (String key : keys) {
            fieldList.append(key.toLowerCase()).append(",");
        }
        fieldList.append("well_id");

        // 准备批量插入的SQL
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO dc_curvedata (").append(fieldList).append(") VALUES ");

        // 获取数据行数（假设所有列表长度相同）
        int dataSize = curveData.values().iterator().next().size();

        // 构建值部分
        StringBuilder valuesPart = new StringBuilder();
        for (int i = 0; i < dataSize; i++) {
            if (i > 0) {
                valuesPart.append(",");
            }
            valuesPart.append("(");

            // 添加每个字段的值
            for (int j = 0; j < keys.size(); j++) {
                if (j > 0) {
                    valuesPart.append(",");
                }
                List<Double> dataList = curveData.get(keys.get(j));
                if (i < dataList.size()) {
                    valuesPart.append(dataList.get(i));
                } else {
                    valuesPart.append("NULL");
                }
            }

            // 添加well_id
            valuesPart.append(",").append(wellId).append(")");
        }

        sql.append(valuesPart);
        //执行sql
        mapperUtils.updataBySql(sql.toString());
    }

    /**
     * 根据井ID查询曲线数据
     * @param wellId
     * @return
     */
    @Override
    public List<Map<String, Object>> getCurveData(Integer wellId, Integer currentPage, Integer pageSize) {
        return mapperUtils.queryBySql("select * from dc_curvedata where well_id=" + wellId + " limit " + pageSize + " offset " + (currentPage - 1) * pageSize);
    }
}
